package libs

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	mathrand "math/rand"
	"net"
	"net/http"
	"strings"
	"time"
)


//获得本机ip
func ReturnCurrentIp() string {
	var ips []string
	addrs, _ := net.InterfaceAddrs()
	for _, a := range addrs {
		if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() && ipnet.IP.To4() != nil {
			ips = append(ips, ipnet.IP.String())
		}
	}
	return ips[0]
}


/**
 * ReturnJson function
 * 通用返回信息
 * @return void
 * @author LeixiaoTian
 */
func ReturnJson(code int, msg string, result interface{}) interface{} {
	content := make(map[string]interface{})
	content["code"] = code

	if msg != "" {
		content["msg"] = msg
	} else {
		content["msg"] = MsgCode[code]
	}

	//如果result是[]byte无法转成json数据，需要先把[]byte转成map
	//gin把数据转成json只有map和结构体
	var data interface{}
	switch  result.(type) {
	case []uint8 :
		m := make(map[string]interface{})
		err := json.Unmarshal(result.([]byte), &m)
		if err != nil {
			fmt.Println("Umarshal failed:", err)
			return nil
		}
		data = m
	default :
		data = result
	}
	//如果为nil返回结果集为空
	if data == nil {
		data = []int{}
	}
	content["data"] = data
	content["timemap"] = time.Now().Unix()
	return content
}

func Res(data interface{}) []byte {
	msg, _ := json.Marshal(data)
	return msg
}

//返回订单号
func ReturnOrderSn(prefix string) string {
	rand := fmt.Sprintf("%06v", mathrand.New(mathrand.NewSource(time.Now().UnixNano())).Int31n(100000000))
	return prefix + time.Now().Format("20060102150405") + rand
}

//http函数
func HttpRequest(method, url, parrams string) ([]byte, error) {

	client := &http.Client{}

	req, err := http.NewRequest(method, url, nil)
	if err != nil {
		log.Println("[验证银行卡失败]" + err.Error())
	}

	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "APPCODE 5ce2686147d944e9b404010c7e409f40")

	resp, err := client.Do(req)
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Println("[验证银行卡失败]" + err.Error())
	}
	return body, err
}

//http请求函数封装
func HttpDo(method, url, params, contentType string) ([]byte, error) {
	fmt.Println("params:",params)
	client := &http.Client{}

	var (
		req *http.Request
		err error
	)

	req, err = http.NewRequest(method, url, strings.NewReader(params))
	if err != nil {
		log.Println(err)
	}

	//设置请求内容类型 默认json
	req.Header.Set("Content-Type", "application/json")

	resp, err := client.Do(req)
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Println(err)
	}
	fmt.Println("body:",string(body))
	bodyMap := make(map[string]interface{})
	err = json.Unmarshal(body, &bodyMap)
	if err != nil {
		fmt.Println("Umarshal failed:", err)
		return nil, err
	}
	fmt.Println("bodyMap:", bodyMap)
	if _, ok := bodyMap["code"]; ok && bodyMap["code"] != "200" {
		return nil, errors.New(bodyMap["status"].(string)+bodyMap["detail"].(string))
	}
	if len(body) <= 2{
		return nil, errors.New("获取数据失败")
	}
	return body, nil
}

//struct转json字符串
func StructToJson(data interface{}) string {

	byteStr, _ := json.Marshal(data)
	return string(byteStr)

}

//定义消息容器
var MsgCode map[int]string = map[int]string{
	200: "成功",
	400: "客户端请求的语法错误，服务器无法理解",
	403: "服务器理解请求客户端的请求，但是拒绝执行此请求",
	404: "请求的资源不存在",
	405: "客户端请求中的方法被禁止",
	408: "服务器等待客户端发送的请求时间过长，超时",
	500: "内部服务器错误",
	501: "服务器不支持请求的功能，无法完成请求",
}